<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单状态" prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" placeholder="请选择订单状态" clearable style="width: 160px;">
          <el-option v-for="dict in team_order_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单时间" prop="orderTime">
        <el-date-picker
          v-model="queryParams.orderTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD"
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">筛选</el-button>
        <el-button
          type="text"
          style="font-size: 12px; padding: 0 8px; background: none; border: none;"
          icon="Refresh"
          @click="resetQuery"
        >清空筛选条件</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['order:order:export']"
        >导出订单</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column label="服务名称" align="center" prop="serviceNames">
        <template #default="scope">
          <span>{{ Array.isArray(scope.row.serviceNames) ? scope.row.serviceNames.join(', ') : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="买家" align="center" prop="userName">
        <template #default="scope">
          <span>{{ scope.row.userName || '-' }}<template v-if="scope.row.userPhone">（{{ scope.row.userPhone }}）</template></span>
        </template>
      </el-table-column>
      <el-table-column label="商家" align="center" prop="merchantName">
        <template #default="scope">
          <span>{{ scope.row.merchantName || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="价格" align="center">
        <template #default="scope">
          <div>
            <div>原价: ￥{{ (scope.row.totalPrice ?? 0).toFixed(2) }}</div>
            <div>优惠: ￥{{ (scope.row.discountPrice ?? 0).toFixed(2) }}</div>
            <div>实付: ￥{{ (scope.row.payPrice ?? 0).toFixed(2) }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="orderStatus">
        <template #default="scope">
          <dict-tag :options="team_order_status" :value="scope.row.orderStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="预约时间" align="center" prop="reservationTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reservationTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="payTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.payTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            type="text"
            size="small"
            style="color: #409EFF; padding: 0 8px; font-weight: bold;"
            @click="goToDetail(scope.row.orderId)"
          >
            <i class="el-icon-view" style="margin-right: 4px;"></i>详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="orderRef" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="goToDetail(form.orderId)">详情</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Order">
import { listOrder, getOrder} from "@/api/order/order"

const { proxy } = getCurrentInstance()
const { team_order_status } = proxy.useDict('team_order_status')

const orderList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderNo: null,
    orderStatus: null,
    orderTime: [],
    serviceTypeId: 3,
  },
  rules: {
    orderNo: [
      { required: true, message: "订单编号不能为空", trigger: "blur" }
    ],
    merchantId: [
      { required: true, message: "商户ID不能为空", trigger: "blur" }
    ],
    userId: [
      { required: true, message: "下单用户ID不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询订单管理列表 */
function getList() {
  loading.value = true
  listOrder(queryParams.value).then(response => {
    orderList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    orderNo: null,
    merchantName: null,
    userName: null,
    userPhone: null,
    serviceNames: null,
    totalPrice: null,
    discountPrice: null,
    payPrice: null,
    payType: null,
    payStatus: null,
    orderStatus: null,
    reservationTime: null,
    payTime: null,
    createTime: null,
    // 其他表格中有的字段可继续补充
  }
  proxy.resetForm("orderRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('admin/order/export', {
    ...queryParams.value
  }, `order_${new Date().getTime()}.xlsx`)
}

// 跳转到订单详情页
function goToDetail(orderId) {
  if (!orderId) {
    proxy.$message.error('未获取到订单ID')
    return
  }
  proxy.$router.push({
    path: '/order/wash/detail',
    query: { id: orderId }
  })
}

getList()
</script>

<style scoped>
.app-container {
  padding: 24px;
}
.el-form {
  margin-bottom: 16px;
}
.el-form-item {
  margin-right: 24px;
}
.el-button + .el-button {
  margin-left: 8px;
}
.el-table {
  margin-top: 16px;
}
</style>
